﻿using SqlSugar;

namespace JunionRobotTaskManager.Models
{
    public class CalibrationInfo
    {
        /// <summary>
        /// 是否在标定中
        /// </summary>
        public bool IsCalibrating { get; set; }

        /// <summary>
        /// 电量达到100后计时中
        /// </summary>
        public bool IsTiming { get; set; }

        /// <summary>
        /// 标定计时开始时间
        /// </summary>
        public DateTime? StartTime { get; set; }

        /// <summary>
        /// 上次标定日期
        /// </summary>
        public DateTime? LastCalibrationDate { get; set; }

        /// <summary>
        /// 标定配置
        /// </summary>
        public CalibrationSettings CalibrationSettings { get; set; }

        /// <summary>
        /// 获取已标定时长
        /// </summary>
        /// <returns></returns>
        public int GetCalibrationSpan()
        {
            if (this.IsCalibrating)
            {
                return (int)(DateTime.Now - this.StartTime.Value).TotalMinutes;
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// 开始标定
        /// </summary>
        public bool Enable()
        {
            if (this.CalibrationSettings==null) 
            {
                throw new Exception("CalibrationSettings is null");
            }
            if (this.CalibrationSettings.EnableCalibration)
            {
                if (this.LastCalibrationDate == null)  //每次重启都会重新计时
                {
                    this.LastCalibrationDate = DateTime.Now;
                }
                if (this.LastCalibrationDate == null ||              //每次重启都会重新标定，目前现场用的是这个
                    (DateTime.Now - this.LastCalibrationDate.Value).TotalMinutes >= CalibrationSettings.TimeNode)
                {
                    var time = DateTime.Now.TimeOfDay;
                    if (time >= CalibrationSettings.CalibrationEnableStartTime && time < CalibrationSettings.CalibrationEnableEndTime)
                    {
                        this.IsCalibrating = true;
                        this.LastCalibrationDate = DateTime.Now;
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 标定是否完成
        /// </summary>
        /// <returns></returns>
        public bool IsComplete() => this.GetCalibrationSpan() > this.CalibrationSettings.CalibrationSpan;

        /// <summary>
        /// 电量达到100后开始计时
        /// </summary>
        public void StartTimer()
        {
            this.IsTiming = true;
            this.StartTime = DateTime.Now;
        }

        /// <summary>
        /// 状态重置
        /// </summary>
        public void Reset()
        {
            this.IsCalibrating = false;
            this.IsTiming = false;
            this.StartTime = null;
        }
    }
}
